#!/usr/bin/python2.4

#we get two parameters repo-path and txn no

#we perform the following checks:
#	1. there was some log
# 	2. log started with a bug no: BUG:xyz, first word, no space allwoed
#	3. bug exists 
#	4. is assigned to the committer
# 	5. is in open accepted state. 
# Hello World
import sys, os
import commands
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='/home/example/hooks.log',
                    filemode='a')
sys.path += ["/home/amitu/python_modules"]
os.environ["PYTHONPATH"] = "/home/amitu/python_modules"
os.environ["PATH"] = "/home/amitu/bin:/usr/bin"
os.environ["HOME"] = "/home/example/repo"

def main():
    # get the parameters
    try: _, repo, txn = sys.argv
    except Exception, e: 
        logging.exception("Failure while unpacking arguments.")
        print >> sys.stderr, "Not enough arguments to script. "
        sys.exit(1)
    # to get log message, we have to call:
    #       $ svnlook log -t txn repo
    # and use the output
    stat, log = commands.getstatusoutput("svnlook log -t %s %s" % (txn, repo))
    if stat: 
        logging.error("svnlook exited with non zero exit code: %s" % log)
        print >> sys.stderr, "svnlook exited with non zero exit code:", log
        sys.exit(1)
    # we got the log successfully, no implement all the checks:
    # if there is some log
    if not log.strip():
        print >> sys.stderr, "Empty log message, please enter BUG:bug no followed by log msg."
        sys.exit(1)
    log = log.lstrip()
    parts = log.split(" ", 1)
    if len(parts) != 2 or parts[1].strip() == "": 
        print >> sys.stderr, "Log message should contain BUG no and some message."
        sys.exit(1)
    word = parts[0].strip().lower()
    if not word.startswith("bug:"):
        print >> sys.stderr, "Log message does not begin with BUG:"
        sys.exit(1)
    bug_no = word[4:]
    try: bug_no= int(bug_no)
    except ValueError:
        print >> sys.stderr, "BUG no supplied is not integer."
        sys.exit(1)
    # lets see if bug exists
    stat, output = commands.getstatusoutput('/home/amitu/bin/bugz -b http://bugs.example.com -u checkin-bot@example.com -p "password" get %d' % bug_no)
    if stat:
        print >> sys.stderr, "Bug %s does not exists." % bug_no, output
        sys.exit(1)
    assignee, status = parse_bug(output)
    # get info from the txn
    stat, author = commands.getstatusoutput("svnlook author -t %s %s" % (txn, repo))
    if stat:
        print >> sys.stderr, "Some error getting output from svnlook." % bug_no
        sys.exit(1)
    if assignee != "%s@example.com" % author:
        print >> sys.stderr, "Bug is assigned to %s, you [%s] do not have permission to commit here." % (assignee, author)
        sys.exit(1)
    if status != "ASSIGNED":
        print >> sys.stderr, "BUG is in %s state, please accept bug before committing any changes." % status
        sys.exit(1)

def parse_bug(output):
    lines = output.splitlines()
    assignee = status = ""
    for line in lines: 
        if line.startswith("Assignee"): assignee = line.split(":")[1].strip()
        if line.startswith("Status"): status = line.split(":")[1].strip()
    return assignee, status
    
        
if __name__ == "__main__": main()

